package com.ruoyi.app.strategy.impl;

import com.ruoyi.app.domain.constants.CustomPromptConstant;
import com.ruoyi.app.domain.entity.User;
import com.ruoyi.app.domain.params.UserRegisterParam;
import com.ruoyi.app.mapper.UserMapper;
import com.ruoyi.app.strategy.RegisterStrategy;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.sign.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
public class EmailRegisterStrategyImpl implements RegisterStrategy {

    @Value("${api.captcha.prefix.email}")
    private String EMAIL_PREFIX;

    @Value("${api.account.prefix}")
    private String ACCOUNT_PREFIX;

    @Resource
    private RedisCache redisCache;

    @Resource
    private UserMapper userMapper;

    @Override
    public void register(UserRegisterParam userRegisterParam) {
        // 获取验证码
        String code = redisCache.getCacheObject(EMAIL_PREFIX + ":" + userRegisterParam.getCode());

        // 校验验证码
        if(Objects.equals(code, userRegisterParam.getTimeCode())){
            User user = User.builder()
                    .code(ACCOUNT_PREFIX + userRegisterParam.getCode())
                    .nickName(userRegisterParam.getCode())
                    .email(userRegisterParam.getCode())
                    .password(Md5Utils.hash(userRegisterParam.getPassword()))
                    .registerType(userRegisterParam.getRegisterType())
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build();

            userMapper.register(user);
        }else {
            throw new ServiceException(CustomPromptConstant.VERIFY_CODE_ERROR);
        }
    }
}
